//
//  XHListVC.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/6/7.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import PullToRefresh
import HandyJSON

class XHListVC: UIViewController ,UITableViewDelegate, UITableViewDataSource {

    static let VCID = "XHListVC"
    
    let tableView: UITableView = UITableView.init(frame: CGRect.init(x: 0, y: UIUtility.kNavigationBarHeight + 44, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT - 108))
    
    let segment = UISegmentedControl.init(items: ["现货","采购"])
    
    var pageNum = 0
    var models:[AnyObject] = []
    let bottomRefreher = PullToRefresh(position: .bottom)
    var listType = "0"
    var cities = ""
    var channels = ""
    
    deinit {
        if let head = tableView.topPullToRefresh{
            self.tableView.removePullToRefresh(at: .top)
        }
        if let btm = tableView.bottomPullToRefresh{
            self.tableView.removePullToRefresh(at: .bottom)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = Const.WTM_WHITE_SMOKE
        self.view.addSubview(self.tableView)
        self.automaticallyAdjustsScrollViewInsets = false
        segment.tintColor = Const.WTM_GREEN
        segment.setWidth(50, forSegmentAt: 0)
        segment.selectedSegmentIndex = 0
        self.navigationItem.titleView = segment
        
        self.tableView.backgroundColor = Const.WTM_WHITE_SMOKE
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorStyle = .none
        self.setupPullToRefresh()
        self.refresh()
        
        self.addBarbuttonItem()
        self.addSegeListener()
        
        self.addButtons()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func addSegeListener() {
        segment.addTarget(self, action: #selector(XHListVC.onChooseSegement(_:)), for: .touchUpInside)
    }
    
    func addBarbuttonItem() {
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "发布", style: .plain, target: self, action: #selector(XHListVC.onTapPublish))
    }
    
    func addButtons() {
    
        let buttonsContainer = UIView.init(frame: CGRect.init(x: 0, y: UIUtility.kNavigationBarHeight, width: Const.SCREEN_WIDTH, height: 44))
        buttonsContainer.backgroundColor = UIColor.white
        let leftView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH/2, height: 44))
        leftView.backgroundColor = buttonsContainer.backgroundColor
        buttonsContainer.addSubview(leftView)
        
        let titleLabel = UILabel.init(frame: leftView.bounds)
        titleLabel.textAlignment = .center
        titleLabel.text = "品种选择"
        leftView.addSubview(titleLabel)
        
        let x = leftView.frame.size.width - 40
        let arrow = UIImageView.init(frame: CGRect.init(x: x, y: 19, width: 11, height: 5))
        arrow.image = UIImage.init(named: "xh_arrow")
        leftView.addSubview(arrow)
        
        leftView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(XHListVC.chooseChannel)))
        
        let rightView = UIView.init(frame: CGRect.init(x: Const.SCREEN_WIDTH/2, y: 0, width: Const.SCREEN_WIDTH/2, height: 44))
        rightView.backgroundColor = buttonsContainer.backgroundColor
        buttonsContainer.addSubview(rightView)
        
        let titleLabel2 = UILabel.init(frame: rightView.bounds)
        titleLabel2.textAlignment = .center
        titleLabel2.text = "地区选择"
        rightView.addSubview(titleLabel2)
        
        let arrow2 = UIImageView.init(frame: CGRect.init(x: x, y: 19, width: 11, height: 5))
        arrow2.image = UIImage.init(named: "xh_arrow")
        rightView.addSubview(arrow2)
        
        rightView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(XHListVC.chooseCity)))
        
        let vLine = UIView.init(frame: CGRect.init(x: Const.SCREEN_WIDTH/2, y: 0, width: 0.5, height: 44))
        vLine.backgroundColor = Const.WTM_GRAY
        buttonsContainer.addSubview(vLine)
        
        let hLine = UIView.init(frame: CGRect.init(x: 0, y: 43.5, width: Const.SCREEN_WIDTH, height: 0.5))
        hLine.backgroundColor = Const.WTM_GRAY
        buttonsContainer.addSubview(hLine)

        
        self.view.addSubview(buttonsContainer)
    }
    
    @objc func chooseChannel() {
        let vc = KXChannelVC.init()
        vc.singleSelect = true
        vc.selected = self.channels.components(separatedBy: ",")
        vc.title = "选择品种"
        vc.onComplete = { channels in
            self.channels = channels.replacingOccurrences(of: ",", with: "")
            self.refresh()
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func chooseCity() {
        let vc = CityVC.init()
        vc.singleSelect = true
        vc.selected = self.cities.components(separatedBy: ",")
        vc.onComplete = { cities in
            self.cities = cities.replacingOccurrences(of: ",", with: "")
            if self.cities == "全部" {
                self.cities = ""
            }
            self.refresh()
        }
        
        self.navigationController?.pushViewController(vc, animated: true)

    }
    
    @objc func onTapPublish() {
        
        let vc:PublishCenterVC = UIStoryboard.init(name: "Xianhuo", bundle: Bundle.main).instantiateViewController(withIdentifier: PublishCenterVC.VCID) as! PublishCenterVC
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func onChooseSegement(_ sender: UISegmentedControl) {
        
        
        switch (sender.selectedSegmentIndex){
        case 0:
            listType = "0"
            break;
        case 1:
            listType = "1"
            break;
        default:
            break;
        }
        
        self.refresh();
    }
    
    func setupPullToRefresh() {
        self.tableView.addPullToRefresh(PullToRefresh()) { [weak self] in
            self?.refresh()
        }
        self.addRefreshFooter()
    }
    
    func addRefreshFooter() -> Void {
        self.tableView.addPullToRefresh(bottomRefreher) { [weak self] in
            if self == nil {
                return
            }
            self!.loadmore()
        }
    }
    
    func removeRefreshFooter() -> Void {
        self.tableView.removePullToRefresh(at: .bottom)
    }

    func refresh() {
        
        let params = ["audit":"1","page":"1","type":self.listType,
                      "channelname":self.channels,"place":self.cities]
        
        _ = NetworkManager.GET(NetworkManager.XIANHUO_LIST,params:params) { (status, response) in
            self.tableView.endRefreshing(at: .top)
            self.models.removeAll()
            
            if(status){
                
                for dic in response.wtmList {
                    let member = JSONDeserializer<XianhuoModel>.deserializeFrom(dict:dic as? NSDictionary)
                    self.models.append(member!)
                }
                self.pageNum += 1
                DispatchQueue.main.async {
                    self.stopLoading()
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func loadmore() {
        let pageNumStr = String(pageNum)
        let params = ["audit":"1","page":pageNumStr,"type":self.listType,
                      "channelname":self.channels,"place":self.cities]
        
        _ = NetworkManager.GET(NetworkManager.XIANHUO_LIST,params:params) { (status, response) in
            self.tableView.endRefreshing(at: .bottom)

            for dic in response.wtmList {
                let member = JSONDeserializer<XianhuoModel>.deserializeFrom(dict:dic as? NSDictionary)
                self.models.append(member!)
            }
            self.pageNum += 1
            if response.wtmList.count < 10 {
                self.removeRefreshFooter()
            }
            DispatchQueue.main.async {
                self.stopLoading()
                self.tableView.reloadData()
            }
        }
    }
    
    func stopLoading(){
        tableView.endRefreshing(at: .top)
        tableView.endRefreshing(at: .bottom)
    }
    
    // MARK :- tableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let xianhuo = models[indexPath.row]
        return self.heightOfXianhuo(xianhuo as! XianhuoModel)
    }
    
    func heightOfXianhuo(_ xianhuo: XianhuoModel) -> CGFloat {
        
        return XianhuoListCell.height
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let xianhuo : XianhuoModel = self.models[indexPath.row] as! XianhuoModel
        
        if let cell:XianhuoListCell = tableView.dequeueReusableCell(withIdentifier: "XianhuoListCell") as? XianhuoListCell {
            self.fillCell(cell,with:xianhuo )
            return cell
        }
        let cell:XianhuoListCell = XianhuoListCell.init(style: .default, reuseIdentifier: "XianhuoListCell")
        self.fillCell(cell,with:xianhuo)
        return cell
    }
    
    func fillCell(_ cell:XianhuoListCell , with:XianhuoModel) {
        cell.categoryTV.text = with.channelname
        cell.locationTV.text = with.place
        cell.companyTV.text = with.company
        cell.factoryTV.text = with.factory
//        cell.qualityTV.text = with.quality
//        cell.specificationTV.text = with.specification
        cell.imgView.kf.setImage(with:URL(string:with.kucunpic))
//        cell.setPrice(with.price)
        cell.dateTV.text = with.getDate()

    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let xianhuo : XianhuoModel = self.models[indexPath.row] as! XianhuoModel
        let vc = XianhuoDetailVC2.init()
        vc.url = vc.SHARE_URL + xianhuo.xianhuoId + "&fromApp=1"
        vc.model = xianhuo
        self.navigationController?.pushViewController(vc, animated: true)
    }

}
